<!-- 角色管理页面 -->
<template>
  <div>
    <el-form v-model="searchMap" :inline="true">
      <el-form-item label="角色名称">
        <el-input v-model="searchMap.name" placeholder="请输入"></el-input>
      </el-form-item>

      <el-form-item label="角色标识">
        <el-input v-model="searchMap.tag" placeholder="请输入"></el-input>
      </el-form-item>

      <el-form-item label="状态">
        <el-select v-model="searchMap.status" clearable placeholder="请选择">
          <el-option
            v-for="item in statusLists"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-button type="primary" @click="fetchData()">查询</el-button>
      <el-button type="primary" @click="handleEdit('')">新增</el-button>
    </el-form>

    <el-table :data="tableData" border stripe style="width: 100%">
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="id" label="序号" width="80"> </el-table-column>
      <el-table-column prop="name" label="角色名称" width="120">
      </el-table-column>
      <el-table-column prop="tag" label="角色标识" width="180">
      </el-table-column>
      <el-table-column prop="pname" label="权限名称" width="200">
      </el-table-column>
      <el-table-column
        prop="created"
        label="创建时间"
        :formatter="dataFormat"
        width="200"
      >
      </el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template scope="scope">
          <el-button
            type="primary"
            v-if="scope.row.status === 0"
            @click="updateStatus(scope.row.id, scope.row.status)"
            >启用</el-button
          >
          <el-button
            type="warning"
            v-if="scope.row.status === 1"
            @click="updateStatus(scope.row.id, scope.row.status)"
            >禁止</el-button
          >
        </template>
      </el-table-column>

      <el-table-column prop="rirht" label="授权" width="120">
        <template scope="scope">
          <el-button
            type="primary"
            @click="open(scope.row.id)"
            icon="el-icon-key"
            size="small"
          >
          </el-button>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="100">
        <template slot-scope="scope">
          <el-button @click="handleEdit(scope.row.id)" type="text" size="small"
            >修改</el-button
          >
          <el-button
            @click="handleDelete(scope.row.id)"
            type="text"
            size="small"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <el-pagination
      @size-change="sizeData"
      @current-change="pageData"
      :page-sizes="[5, 10, 20, 30, 60]"
      :page-size="5"
      layout="total, sizes, prev, pager, next, jumper"
      :total="count"
    >
    </el-pagination>

    <!-- 权限框 -->
    <el-dialog title="授权" :visible.sync="permissionFormVisible">
      <el-form>
        <el-table
          :data="permissionData"
          @selection-change="handleSelectionChange"
          reserve-selection
        >
          <el-table-column
            type="selection"
            width="55"
            :reserve-selection="true"
          >
          </el-table-column>
          <el-table-column
            property="id"
            label="权限ID"
            width="150"
          ></el-table-column>
          <el-table-column
            property="permissionName"
            label="权限名称"
            width="200"
          ></el-table-column>
          <el-table-column
            prop="created"
            label="创建时间"
            :formatter="dataFormat"
            width="200"
          ></el-table-column>
        </el-table>
        <el-form-item style="margin-top: 20px">
          <el-button
            type="primary"
            @click="permissionSave()"
            style="margin-left: 240px"
            >保存</el-button
          >
          <el-button
            @click="permissionFormVisible = false"
            style="margin-left: 10px"
            >关闭</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 添加修改框 -->
    <el-dialog title="编辑" :visible.sync="dialogFormVisible">
      <el-form label-width="80px">
        <el-row>
          <el-col span="11">
            <el-form-item label="角色名称">
              <el-input v-model="role.name" />
            </el-form-item>
          </el-col>
          <el-col span="11">
            <el-form-item label="角色标识">
              <el-input v-model="role.tag" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col span="11">
            <el-form-item label="是否启用">
              <el-radio-group v-model="role.status">
                <el-radio :label="0">启用</el-radio>
                <el-radio :label="1">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col span="11">
            <el-form-item label="备注"
              ><el-input type="textarea" v-model="role.remark"
            /></el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleSave()"
            style="margin-left: 240px"
            >保存</el-button
          >
          <el-button
            @click="dialogFormVisible = false"
            style="margin-left: 10px"
            >关闭</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
  
  <script>
import roleService from "@/api/role.js";
import userService from "@/api/user";
import permissionService from "@/api/permission";
//导入日期组件
import moment from "moment";

export default {
  data() {
    return {
      tableData: [],
      permissionData: [],
      statusLists: [
        {
          label: "启用",
          value: "0",
        },
        {
          label: "禁用",
          value: "1",
        },
      ],
      props: {
        label: "name",
        children: "zones",
      },
      list: [],
      ids: [],
      rolePermissions: [],
      permissionFormVisible: false,
      dialogFormVisible: false,
      id: "",
      role: {},
      searchMap: {
        limit: 5,
        page: 1,
        name: "",
        tag: "",
        status: "",
      },
      statusList: { status: "", id: "" },
      permissionMap: {
        roleId: "",
        permissionIds: [],
      },
      //记录总数
      count: 0,
    };
  },
  //钩子函数
  created() {
    this.findAllUser();
    this.findPermission();
    this.findAll();
    this.fetchData();
  },
  methods: {
    //修改或新增
    handleEdit(id) {
      this.id = id;

      //打开弹窗
      this.dialogFormVisible = true;

      if (id !== "") {
        //根据id查询数据绑定到模型上面
        roleService.find(id).then((response) => {
          //回显
          this.role = response.data;
        });
      } else {
        //清除之前模型的脏数据
        this.role = {};
      }
    },
    //新增和修改的提交
    handleSave() {
      roleService.update(this.id, this.role).then((response) => {
        //新增或者修改成功
        this.$message({
          message: response.msg,
          type: "success",
        });

        //重新加载列表的数据
        this.fetchData();

        //关闭弹窗
        this.dialogFormVisible = false;
      });
    },

    //通过创建人
    findAllUser() {
      userService.findAll().then((response) => {
        this.userList = response.data;
      });
    },

    findAll() {
      roleService.findAll().then((response) => {
        this.list = response.data;
      });
    },
    //查询数据
    fetchData() {
      const data = this.searchMap;
      roleService.list(data).then((response) => {
        this.tableData = response.data;
        this.count = response.count;
      });
    },
    //当页面大小改变的时候调用此方法，传递改变的页面大小
    sizeData(size) {
      this.searchMap.limit = size;
      this.fetchData();
    },
    pageData(page) {
      this.searchMap.page = page;
      this.fetchData();
    },

    //增加一个格式化日期的方法
    dataFormat(row, column) {
      let date = row[column.property];

      if (date == undefined) {
        return "";
      }

      return moment(date).format("YYYY-MM-DD hh:mm:ss");
    },

    //点击修改状态
    updateStatus(id, status) {
      this.$confirm("您确定要修改状态吗, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        if (status === 0) {
          status = 1;
        } else {
          status = 0;
        }
        this.statusList.status = status;
        this.statusList.id = id;
        roleService
          .update(id, this.statusList)
          .then((response) => {
            this.$message({
              type: "success",
              message: "修改状态成功!",
            });

            this.fetchData();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消修改",
            });
          });
      });
    },

    // 处理勾选事件
  handleSelectionChange(selectedPermissions) {
    
  // 更新选中权限ID列表
  this.permissionMap.permissionIds = selectedPermissions.map((item) => item.id);
  this.ids = selectedPermissions.map((item) => item.id);
},

    //查询所有权限
    findPermission() {
      permissionService.findAll().then((response) => {
        this.permissionData = response.data;
      });
    },

  // 打开权限框
open(id) {
   // Uncheck all previously selected permissions
   this.permissionData.forEach((permission) => {
    permission.checked = false;
  });
  this.id = id;
  this.permissionMap.roleId = id;

  // 清空之前可能选中的权限ID列表
  this.permissionMap.permissionIds = [];

  // 查询角色的权限
  permissionService.find(this.permissionMap.roleId).then((response) => {
    this.rolePermissions = response.data; // 假设返回的是权限ID列表
    // 设置所有权限的选中状态
    this.permissionData.forEach((permission) => {
      permission.checked = this.rolePermissions.includes(permission.id);
      // 如果权限被角色拥有，则添加到选中权限ID列表中
      if (permission.checked) {
        this.permissionMap.permissionIds.push(permission.id);
      }
    });
  });
  // 打开弹窗
  this.permissionFormVisible = true;
},


    //修改权限
    permissionSave() {
      this.permissionMap.roleId = this.id;
      this.permissionMap.permissionIds = this.ids
      roleService.updateRolePermission(this.permissionMap).then((response) => {
        //修改成功
        this.$message({
          message: response.msg,
          type: "success",
        });

        //重新加载列表的数据
        this.fetchData();

        //关闭弹窗
        this.permissionFormVisible = false;
      });
    },
    //删除
    handleDelete(id) {
      this.$confirm("您确定要删除吗, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          roleService.remove(id).then((response) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });

            this.fetchData();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>
  